package top.appx.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import top.appx.dao.OrderDao;
import top.appx.entity.OrderEntity;
import top.appx.qo.OrderQO;
import top.appx.util.StringUtil;
import top.appx.vo.Pager;

import java.util.List;

/**
 * Created by john on 2015/7/12.
 */
@Repository
public class OrderDaoImpl extends BaseDaoImpl<OrderEntity> implements OrderDao {

    public Pager<OrderEntity> queryByPage(OrderQO bean, int page, int rows) {
        Criteria c = this.getCurrentSession().createCriteria(OrderEntity.class);
        int total = ((Number)c.setProjection(Projections.rowCount()).uniqueResult()).intValue();
        c.setProjection(null);
        c.addOrder(org.hibernate.criterion.Order.desc("id"));
        c.setFirstResult((page - 1) * rows);
        c.setMaxResults(rows);
        if(bean!=null) {
            if(!StringUtil.isEmptyOrNull(bean.getRname())) {
                c.add(Restrictions.like("rname", "%" + bean.getRname() + "%"));
            }
            if(!StringUtil.isEmptyOrNull(bean.getIp())){
                c.add(Restrictions.like("ip", "%" + bean.getIp() + "%"));
            }
            if(bean.getStatus()!=null && bean.getStatus()!=0){
                c.add(Restrictions.eq("status",bean.getStatus()));
            }
        }
        List list = c.list();
        Pager<OrderEntity> result = new Pager<OrderEntity>();
        result.setTotal(total);
        result.setRows(list);
        return result;
    }

    public OrderEntity queryByIp(String ip) {
        Criteria c = this.getCurrentSession().createCriteria(OrderEntity.class);
        c.add(Restrictions.eq("ip", ip));
        c.setMaxResults(1);
        c.addOrder(Order.desc("id"));

        List<OrderEntity> list = c.list();
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }
}
